package com.lujieni.springbootmybatis.permission.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.MultiDataPermissionHandler;
import com.lujieni.springbootmybatis.aop.DataPermission;
import com.lujieni.springbootmybatis.context.DataPermissionContextHolder;
import com.lujieni.springbootmybatis.permission.rule.DataPermissionRule;
import com.lujieni.springbootmybatis.util.MyBatisUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.conditional.OrExpression;
import net.sf.jsqlparser.schema.Table;

import java.util.List;

@Data
@AllArgsConstructor
public class CustomDataPermissionHandler implements MultiDataPermissionHandler {

    private DataPermissionRule rule;

    @Override
    public Expression getSqlSegment(Table table, Expression where, String mappedStatementId) {
        // 生成条件
        Expression allExpression = null;
        // 已配置，但禁用
        DataPermission dataPermission = DataPermissionContextHolder.get();
        if (dataPermission != null && !dataPermission.enable()) {
            return null;
        }
        // 判断表名是否匹配
        String tableName = MyBatisUtils.getTableName(table);
        if (!rule.getTableNames().contains(tableName)) {
            return allExpression;
        }
        // 单条规则的条件
        Expression oneExpress = rule.getExpression(tableName, table.getAlias());
        if (oneExpress == null) {
            return allExpression;
        }
        // 拼接到 allExpression 中
        allExpression = allExpression == null ? oneExpress : new AndExpression(allExpression, oneExpress);
        return allExpression;
    }

}